Recursion in C++ is a programming technique where a function calls itself to solve a problem. This allows to solve complex problems by breaking them down into smaller, more manageable subproblems. Recursion is often used in situations where a problem it can be naturally divided into smaller, similar instances.
Base Case: Every recursive function should have one or more base cases. These are the simplest scenarios where the function does not call itself and instead provides a direct result. Base cases are essential to prevent infinite recursion.
Recursive Case: In the recursive case, the function calls itself with modified arguments to solve a smaller instance of the same problem. This process continues until a base case is reached.
Here's a simple example of a recursive function that calculates the factorial of a non-negative integer:
#include <iostream>
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: n! = n * (n-1)!
else {
return n * factorial(n - 1);
}
}
int main() {
int num = 5;
int result = factorial(num);
std::cout << "Factorial of " << num << " is " << result << std::endl;
return 0;
}
In this example, the factorial function calculates the factorial of a number n. When n is 0, it returns 1 as the base case. For any other value of n, it recursively calls itself with n - 1 until the base case is reached.
Here are some important points to remember when working with recursion:
question
question2